/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.javanile.young.sms;

import java.io.IOException;

import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

import javax.wireless.messaging.*;


/**
 * An example MIDlet displays text from an SMS MessageConnection
 */
public class Server implements Runnable, MessageListener {
    public class SMSSender implements Runnable {


		/** The port on which we send SMS messages */
		String smsPort;

		/** The URL to send the message to */
		String destinationAddress;


		/**
		 * Initialize the MIDlet with the current display object and
		 * graphical components.
		 */
		public SMSSender(String smsPort) {
			this.smsPort = smsPort;
			this.destinationAddress = null;

		}

		/**
		 * Prompt for message and send it
		 */
		public void promptAndSend(String destinationAddress) {
			this.destinationAddress = destinationAddress;
			new Thread(this).start();
		}

		/**
		 * Respond to commands, including exit
		 * @param c user interface command requested
		 * @param s screen object initiating the request
		 */

		/**
		 * Send the message. Called on a separate thread so we don't have
		 * contention for the display
		 */
		public void run() {
			String address = destinationAddress + ":" + smsPort;

			MessageConnection smsconn = null;

			try {
				/** Open the message connection. */
				smsconn = (MessageConnection)Connector.open(address);

				TextMessage txtmessage =
					(TextMessage)smsconn.newMessage(MessageConnection.TEXT_MESSAGE);
				txtmessage.setAddress(address);
				txtmessage.setPayloadText("Ciao");
				smsconn.send(txtmessage);
			} catch (Throwable t) {
				System.out.println("Send caught: ");
				t.printStackTrace();
			}

			if (smsconn != null) {
				try {
					smsconn.close();
				} catch (IOException ioe) {
					System.out.println("Closing connection caught: ");
					ioe.printStackTrace();
				}
			}
		}
	}



    /** instance of a thread for asynchronous networking and user interface. */
    Thread thread;

    /** Connections detected at start up. */
    String[] connections;

    /** Flag to signal end of processing. */
    boolean done;

    /** The port on which we listen for SMS messages */
    String smsPort;

    /** SMS message connection for inbound text messages. */
    MessageConnection smsconn;

    /** Current message read from the network. */
    Message msg;

    /** Address of the message's sender */
    String senderAddress;


    /** Prompts for and sends the text reply */
    SMSSender sender;


    /**
     * Initialize the MIDlet with the current display object and
     * graphical components.
     */
    public Server() {
        //smsPort = getAppProperty("SMS-Port");


		smsPort = "50001";
        sender = new SMSSender(smsPort);


    }

    /**
     * Start creates the thread to do the MessageConnection receive
     * text.
     * It should return immediately to keep the dispatcher
     * from hanging.
     */
    public void startApp() {
        /** SMS connection to be read. */
        String smsConnection = "sms://:" + smsPort;

        /** Open the message connection. */
        if (smsconn == null) {
            try {
                smsconn = (MessageConnection)Connector.open(smsConnection);
                smsconn.setMessageListener(this);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }

        /** Initialize the text if we were started manually. */
        connections = PushRegistry.listConnections(true);

        if ((connections == null) || (connections.length == 0)) {
            //content.setString("Waiting for SMS on port " + smsPort + "...");
        }

        done = false;
        thread = new Thread(this);
        thread.start();


    }

    /**
     * Notification that a message arrived.
     * @param conn the connection with messages available
     */
    public void notifyIncomingMessage(MessageConnection conn) {
        if (thread == null) {
            done = false;
            thread = new Thread(this);
            thread.start();
        }
    }

    /** Message reading thread. */
    public void run() {
		System.out.println("MSG");
        /** Check for sms connection. */
        try {
            msg = smsconn.receive();

            if (msg != null) {
                senderAddress = msg.getAddress();

                if (msg instanceof TextMessage) {
                } else {
                    StringBuffer buf = new StringBuffer();
                    byte[] data = ((BinaryMessage)msg).getPayloadData();

                    for (int i = 0; i < data.length; i++) {
                        int intData = (int)data[i] & 0xFF;

                        if (intData < 0x10) {
                            buf.append("0");
                        }

                        buf.append(Integer.toHexString(intData));
                        buf.append(' ');
                    }

                }

            }
        } catch (IOException e) {
            // e.printStackTrace();
        }
    }

    /**
     * Pause signals the thread to stop by clearing the thread field.
     * If stopped before done with the iterations it will
     * be restarted from scratch later.
     */
    public void pauseApp() {
        done = true;
        thread = null;
    }

    /**
     * Destroy must cleanup everything.  The thread is signaled
     * to stop and no result is produced.
     * @param unconditional true if a forced shutdown was requested
     */
    public void destroyApp(boolean unconditional) {
        done = true;
        thread = null;

        if (smsconn != null) {
            try {
                smsconn.close();
            } catch (IOException e) {
                // Ignore any errors on shutdown
            }
        }
    }

    /**
     * Respond to commands, including exit
     * @param c user interface command requested
     * @param s screen object initiating the request
     */
    public void commandAction(Command c, Displayable s) {
        /*
		try {
            if ((c == exitCommand) || (c == Alert.DISMISS_COMMAND)) {
                destroyApp(false);
                notifyDestroyed();
            } else if (c == replyCommand) {
                reply();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
		 *
		 */
    }

    /**
     * Allow the user to reply to the received message
     */
    private void reply() {
        // remove the leading "sms://" for displaying the destination address
        String address = senderAddress.substring(6);
        String statusMessage = "Sending message to " + address + "...";
        //sendingMessageAlert.setString(statusMessage);
        sender.promptAndSend(senderAddress);
    }

	public void send(String message, String number) {
		sender.promptAndSend("sms://"+number);
	}
}